<?php
/**
 * Created by PhpStorm.
 * User:tsingStar
 * Date: 2019/7/13
 * Time: 15:06
 */

namespace app\common\model;


use think\Db;
use think\Exception;

class Cart
{

    /**
     * 获取用户购物车商品数量
     */
    public static function getCartNums($user_id)
    {
        $cart_num = db("goods_car")->where('uid', $user_id)->sum("num");
        return $cart_num;
    }

    /**
     * 会员添加购物车
     * @param $user_id
     * @param $goods_id
     * @param $spec_id
     * @param $num
     * @return string
     * @throws UserException
     */
    static public function addCar($user_id, $goods_id, $spec_id, $num)
    {

        if (empty($num)) {
            throw new UserException('请选择商品数量！');
        }
        $info = Goods::check($goods_id);
        $pre = \db("presell")->where("id", $info["presell_id"])->find();
        if($pre["end_time"]>=time()){
            throw new Exception("预售时间过后可购买");
        }
        $where = ['uid' => $user_id, 'goods_id' => $goods_id, 'spec_id' => $spec_id];
        $exist = db('goods_car')->where($where)->find();
        if ($exist) {
            $total = $exist['num'] + $num;
        } else {
            $count = self::getCartNums($user_id);
            if ($count >= config('car_max')) {
                throw new UserException('已达到购物车容量限制' . config('car_max') . '件，请清理部分再来添加！');
            }
            $total = $num;
        }

        if ($info['use_spec'] == 1) {
            if (empty($spec_id)) {
                $str = empty($info['spec_name']) ? '规格' : $info['spec_name'];
                throw new UserException('请选择' . $str . '！');
            }
            $spec = Db::name('goods_spec')->where(['id' => $spec_id, 'goods_id' => $goods_id])->find();
            if (!$spec) {
                throw new UserException('该规格商品已下架！');
            }

            if ($spec['stock'] < $total) {
                throw new UserException('该规格商品库存不足！');
            }
        } else {
            if (!empty($spec_id)) {
                throw new UserException('该商品已关闭规格，请刷新商品后重新选择');
            }
            if ($info['stock'] < $total) {
                throw new UserException('该商品库存不足！');
            }
        }

        //限购
        $maxbuy = $info['maxbuy'];//单次
        $allbuy = $info['allbuy'];//每人总共

        $user_allbuy = self::userAllBuy($user_id, $goods_id);
        $total2 = $total + $user_allbuy;
        if ($exist) {

            if ($maxbuy > 0 && $total > $maxbuy) {
                throw new UserException('该商品每次限购' . $maxbuy . '件！购物车中已有' . $exist['num'] . '件！');
            }
            if ($allbuy > 0 && $total2 > $allbuy) {
                $strs = '该商品每人限购' . $allbuy . '件！购物车中已有' . $exist['num'] . '件！';
                if (!empty($user_allbuy)) {
                    $strs .= '已下单' . $user_allbuy . '件！';
                }
                throw new UserException($strs);
            }
            $data = [
                'update_time' => now_datetime(),
                'num' => $total
            ];
            Db::name('goods_car')->where($where)->update($data);
        } else {
            if ($maxbuy > 0 && $total > $maxbuy) {
                throw new UserException('该商品每次限购' . $maxbuy . '件！');
            }
            if ($allbuy > 0 && $total2 > $allbuy) {
                $strs = '该商品每人限购' . $allbuy . '件！';
                if (!empty($user_allbuy)) {
                    $strs .= '已下单' . $user_allbuy . '件！';
                }
                throw new UserException($strs);
            }
            $data = [
                'uid' => $user_id,
                'goods_id' => $goods_id,
                'spec_id' => $spec_id,
                'num' => $num,
                'create_time' => now_datetime(),
                'update_time' => now_datetime(),
            ];
            Db::name('goods_car')->insert($data);
        }

        return '添加购物车成功';

    }

    /**
     * 校验会员身份是否合法
     */
    private static function checkGoodsLegal($brand_id, $user_id)
    {
        $user = User::exists($user_id);
        return in_array($brand_id, explode(",", $user["brand_id"]));
    }
    /**
     * 会员购物车列表
     */
    static public function carList($user_id)
    {
        $list = \db("goods_car")->alias("a")->join("goods b", "a.goods_id=b.id")->where("a.uid", $user_id)->field("a.id cart_id, a.spec_id spec_id, a.goods_id goods_id, a.num cart_num, b.title, b.use_spec, b.price, b.brand_id, b.stock, b.status, b.minbuy, b.img_url")->select();
        $data_arr = [];
        $del_id = [];
        foreach ($list as $item) {
            $arr = $item;
            //校验身份
            if(!self::checkGoodsLegal($item["brand_id"], $user_id)){
                $del_id[] = $item["cart_id"];
                continue;
            }
            //商品是否还存在
            if ($item["status"] == 0) {
                $del_id[] = $item["cart_id"];
                continue;
            }
            if ($item["use_spec"] == 0) {
                //无规格
                if ($item["stock"] > 0) {
                    if ($item["cart_num"] <= $item["stock"]) {
                        //库存充足
                        if ($item["minbuy"] > 0) {
                            if ($item["cart_num"] < $item["minbuy"]) {
                                $del_id[] = $item["cart_id"];
                                continue;
                            }
                        }
                    } else {
                        //库存不足购物车数量
                        $del_id[] = $item["cart_id"];
                        continue;

                    }
                } else {
                    //库存为空
                    $del_id[] = $item["cart_id"];
                    continue;
                }

            } else {
                //有规格
                if (empty($item["spec_id"])) {
                    $del_id[] = $item["cart_id"];
                    continue;
                }
                $spec = \db("goods_spec")->where("goods_id", $item["goods_id"])->where("id", $item["spec_id"])->find();
                if (empty($spec)) {
                    $del_id[] = $item["cart_id"];
                    continue;
                }
                if ($spec["stock"] > 0) {
                    if ($item["cart_num"] <= $spec["stock"]) {
                        //库存充足
                        if ($item["minbuy"] > 0) {
                            if ($item["cart_num"] < $item["minbuy"]) {
                                $del_id[] = $item["cart_id"];
                                continue;
                            }
                        }
                    } else {
                        //库存不足购物车数量
                        $del_id[] = $item["cart_id"];
                        continue;

                    }
                } else {
                    //库存为空
                    $del_id[] = $item["cart_id"];
                    continue;
                }
                $arr["price"] = $spec["price"];
                $arr["img_url"] = $spec["img_url"];
                $arr["title"] = $arr["title"]."-".$spec["title"];
            }
            $data_arr[] = $arr;
        }
        \db("goods_car")->whereIn("id", $del_id)->delete();
        return [
            "info" => "过期、库存不足商品已自动过滤",
            "data" => $data_arr
        ];
    }

    /**
     * 购物车商品删除
     * @param $user_id
     * @param $car_id
     * @return string
     */
    static public function carRemove($user_id, $car_id)
    {
        if(is_array($car_id)){
            $del = Db::name('goods_car')
                ->whereIn('id', $car_id)
                ->where('uid', $user_id)
                ->delete();
        }else{
            $del = Db::name('goods_car')
                ->where('id', $car_id)
                ->where('uid', $user_id)
                ->delete();
        }
        return '购物车商品删除成功！';
    }

    /**
     * 购物车商品数量增减
     * @param $user_id
     * @param $type
     * @param $car_id
     * @param int $num
     * @return string
     * @throws DeveloperException
     * @throws UserException
     */
    static public function carAddDelete($user_id, $type, $car_id, $num = 1)
    {
        $car = Db::name('goods_car')
            ->alias('gc')
            ->join('__GOODS__ g', 'g.id=gc.goods_id', 'LEFT')
            ->where('gc.id', $car_id)
            ->where('gc.uid', $user_id)
            ->field('gc.num,gc.goods_id,gc.spec_id,g.status,g.stock,g.use_spec,g.minbuy,g.maxbuy,g.allbuy')
            ->find();
        if (!$car) {
            throw new UserException('无此购物车记录，请清理此条记录后再操作！');
        }

        if ($car['status'] != 1) {
            throw new UserException('该商品已下架！');
        }

        if ($car['stock'] <= 0) {
            throw new UserException('该商品已售罄！');
        }

        if ($car['use_spec'] == 1) {
            if (empty($car['spec_id'])) {
                throw new UserException('该商品已启用规格！请清理后重新选择！');
            }

            $spec = Db::name('goods_spec')->where(['id' => $car['spec_id'], 'goods_id' => $car['goods_id']])->find();
            if (!$spec) {
                throw new UserException('该规格商品已下架！请清理后重新选择！');
            }

            if ($spec['stock'] <= 0) {
                throw new UserException('该规格商品已售罄！请清理后重新选择！');
            }

        } else {
            $spec = false;
        }

        if ($type == 0) {
            //减
            $num_total = $car['num'] - 1;
            if ($car['minbuy'] > 0 && $num_total < $car['minbuy']) {
                throw new UserException('该商品' . $car['minbuy'] . '件起售，不能再减了！');
            }
            if ($num_total < 1) {
                throw new UserException('就剩1件了，不能再减了！');
            }
        } elseif ($type == 1) {
            //加
            $num_total = $car['num'] + 1;
            if (!$spec) {
                if ($car['stock'] < $num_total) {
                    throw new UserException('该商品库存不足，不能再加了！');
                }
            } else {
                if ($spec['stock'] < $num_total) {
                    throw new UserException('该规格商品库存不足，不能再加了！');
                }
            }

            if ($car['maxbuy'] > 0 && $num_total > $car['maxbuy']) {
                throw new UserException('该商品每次限购' . $car['maxbuy'] . '件，不能再加了！');
            }

            if ($car['allbuy'] > 0) {
                $user_allbuy = self::userAllBuy($user_id, $car['goods_id']);
                $all = $num_total + $user_allbuy;
                if ($all > $car['allbuy']) {
                    $strs = '该商品每人限购' . $car['allbuy'] . '件';
                    if ($user_allbuy > 0) {
                        $strs .= '已下单' . $user_allbuy . '件，';
                    }
                    $strs .= '，不能再加了！';
                    throw new UserException($strs);
                }
            }

        } else {
            throw new DeveloperException('type仅支持0或1 0减1加');
        }

        $data = [
            'update_time' => now_datetime(),
            'num' => $num_total
        ];

        Db::name('goods_car')
            ->where('id', $car_id)
            ->where('uid', $user_id)
            ->update($data);

        if ($type == 0) {
            return '减少成功';
        } else {
            return '增加成功';
        }
    }

    /**
     * 获取会员已购某件商品的总数
     * @param $user_id
     * @param $goods_id
     * @return float|int
     */
    static public function userAllBuy($user_id, $goods_id)
    {
        $user_allbuy = Db::name('order_goods')->where(['uid' => $user_id, 'goods_id' => $goods_id])->sum('num');
        $user_allbuy = empty($user_allbuy) ? 0 : $user_allbuy;
        return $user_allbuy;
    }


}